package seg.tef4.whms.activity;

import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.scan.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import seg.tef4.whms.activity.activityinit.SubBaseActivity;
import seg.tef4.whms.apis.EquipmentApi;
import seg.tef4.whms.apis.OutWarehouseApi;
import seg.tef4.whms.apis.SparePartApi;
import seg.tef4.whms.component.EquipmenteRecycleView;
import seg.tef4.whms.component.OutWarehouseRecycleView;
import seg.tef4.whms.domain.TEquipment;
import seg.tef4.whms.domain.TOutWarehouse;
import seg.tef4.whms.domain.TSparePart;
import seg.tef4.whms.domain.entity.SysUser;
import seg.tef4.whms.util.auth.OnlineUser;
import seg.tef4.whms.util.dialog.AlertDialogCreator;
import seg.tef4.whms.util.retrofitutil.RetrofitUtil;

public class EquipmentActivity extends SubBaseActivity {

    /**
     * 整体布局
     **/
    private DrawerLayout equipment_drawer_layout;
    private LinearLayout equipment_filter_drawer;
    private LinearLayout out_warehouse_filter_main;

    /**
     * 下拉列表
     **/
    private Spinner equipment_line_spinner;
    private Spinner equipment_station_spinner;
    private Spinner equipment_status_spinner;

    /** 查询filter **/
    private EditText equipment_serial_no_editview;
    private EditText equipment_equip_name_editview;


    private EditText equipment_sop_time;



    private EquipmentApi equipmentApi = (EquipmentApi)  RetrofitUtil.getApiInstance(EquipmentApi.class);



    /** 分页属性 **/
    private int pageNum = 1;

    private int pageSize = 200;

    private List<TEquipment> tEquipments;

    private Long total = Long.MAX_VALUE;

    private RecyclerView recyclerView;

    /** 按钮 **/


    private Button equipment_filter_button;
    private Button equipment_search_button;
    private Button equipment_reset_button;
    private Button equipment_top_button;






    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equipment);
        /**
         * 整体布局
         **/
        equipment_drawer_layout = findViewById(R.id.equipment_drawer_layout);
        equipment_filter_drawer = findViewById(R.id.equipment_filter_drawer);
        out_warehouse_filter_main = findViewById(R.id.equipment_filter_main);
        /**
         * 下拉列表
         **/
        equipment_line_spinner = findViewById(R.id.equipment_line_spinner);
        equipment_station_spinner = findViewById(R.id.equipment_station_spinner);
        equipment_status_spinner = findViewById(R.id.equipment_status_spinner);

        /** 查询filter **/
        equipment_serial_no_editview = findViewById(R.id.equipment_serial_no_editview);
        equipment_equip_name_editview = findViewById(R.id.equipment_equip_name_editview);

        /** button **/
        equipment_search_button = findViewById(R.id.equipment_search_button);
        equipment_reset_button = findViewById(R.id.equipment_reset_button);
        equipment_filter_button = findViewById(R.id.equipment_filter_button);
        equipment_top_button = findViewById(R.id.equipment_top_button);



        tEquipments = new ArrayList<>();
        recyclerView = findViewById(R.id.equipment_RecyclerView);
        LinearLayoutManager layoutManager = new LinearLayoutManager(EquipmentActivity.this);
        recyclerView.setLayoutManager(layoutManager);

        spinnerInit();
        dateSelectorInit();
        equipment_filter_button.setOnClickListener(view -> {
            drawerControl();
        });

        equipment_top_button.setOnClickListener(view -> {
            recyclerView.scrollToPosition(0);
        });



        DataInit();
        equipment_search_button.setOnClickListener(view -> {
            // drawerControl();
            this.queryEquipment(true);

        });

        equipment_reset_button.setOnClickListener(view -> {
            EquipmentActivity.this.pageNum = 1;
            EquipmentActivity.this.total = Long.MAX_VALUE;
            equipment_serial_no_editview.setText(null);
            equipment_equip_name_editview.setText(null);
            equipment_sop_time.setText("");
            equipment_line_spinner.setSelection(0);
            equipment_station_spinner.setSelection(0);
            equipment_status_spinner.setSelection(0);
            queryEquipment(true);
        });


    }

    /**
     * 日期选择初始化
     */
    private void dateSelectorInit(){
        equipment_sop_time = findViewById(R.id.equipment_sop_time);
        Calendar sopCalendar = Calendar.getInstance();
        equipment_sop_time.setOnClickListener(v -> {
            new DatePickerDialog(
                    EquipmentActivity.this,R.style.CustomDatePickerDialog,
                    (view, year, month, dayOfMonth) -> {
                        sopCalendar.set(Calendar.YEAR, year);
                        sopCalendar.set(Calendar.MONTH, month);
                        sopCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                        // 将时、分、秒设置为0
                        sopCalendar.set(Calendar.HOUR_OF_DAY, 0);
                        sopCalendar.set(Calendar.MINUTE, 0);
                        sopCalendar.set(Calendar.SECOND, 0);
                        sopCalendar.set(Calendar.MILLISECOND, 0);
                        equipment_sop_time.setText(year+"-"+(month+1)+"-"+dayOfMonth);
                    },
                    sopCalendar.get(Calendar.YEAR),
                    sopCalendar.get(Calendar.MONTH),
                    sopCalendar.get(Calendar.DAY_OF_MONTH)
            ).show();
        });
    }

    public static void startEquipmentActivity(Context context) {
        context.startActivity(new Intent(context, EquipmentActivity.class));
    }

    /**
     * @description 侧边栏初始化
     */
    private void drawerControl() {
        if (equipment_drawer_layout.isDrawerOpen(equipment_filter_drawer))
            equipment_drawer_layout.closeDrawer(equipment_filter_drawer);
        else
            equipment_drawer_layout.openDrawer(equipment_filter_drawer);
    }

    /**
     * @description 产线选择项初始化
     */
    private void spinnerInit() {
        // 获取产线的所有选项
        equipmentApi.getProductLine(OnlineUser.getToken(EquipmentActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(EquipmentActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        equipment_line_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
        // 设置监听
        equipment_line_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String selected_line = (String) adapterView.getItemAtPosition(i);
                // 获取对应产线的所有工位
                equipmentApi.getStation(OnlineUser.getToken(EquipmentActivity.this), selected_line).enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            String resultJson = response.body().string();
                            JSONObject result = new JSONObject(resultJson);
                            int code = result.getInt("code");
                            String msg = result.getString("msg");
                            if (code == 200) {
                                JSONArray jsonArrays = result.getJSONArray("rows");
                                List<String> lines = new ArrayList<>();
                                lines.add("【请选择】");
                                for (int i = 0; i < jsonArrays.length(); i++) {
                                    JSONObject jsonObject = jsonArrays.getJSONObject(i);
                                    String name = jsonObject.getString("name");
                                    String equipmentName = jsonObject.getString("value");
                                    lines.add(name+"\n"+equipmentName);
                                }
                                ArrayAdapter<String> adapter = new ArrayAdapter<String>(EquipmentActivity.this,
                                        R.layout.spinner_item, lines);
                                adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
                                equipment_station_spinner.setAdapter(adapter);
                            } else {
                                throw new RuntimeException(code + ":" + msg);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                                    "系统错误", e.toString(), "确认", null).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                                "系统错误", t.toString(), "确认", null).show();
                    }
                });

            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });

        // 设备状态
        equipmentApi.getStatus(OnlineUser.getToken(EquipmentActivity.this)).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    if (code == 200) {
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        List<String> lines = new ArrayList<>();
                        lines.add("【请选择】");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            String name = jsonObject.getString("name");
                            lines.add(name);
                        }
                        ArrayAdapter<String> adapter = new ArrayAdapter<String>(EquipmentActivity.this,
                                R.layout.spinner_item, lines);
                        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        equipment_status_spinner.setAdapter(adapter);
                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });


    }

    private void DataInit(){
        queryEquipment(true);
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (!recyclerView.canScrollVertically(1)) {
                    EquipmentActivity.this.pageNum +=1;
                    queryEquipment(false);

                }

            }
        });


    }

    /**
     * @description 零件查询
     */
    private void queryEquipment(boolean initMark){
        if(!initMark && (long) pageNum * pageSize >= total)
            return;
        Map<String,String> params = new HashMap<>();
        params.put("pageNum",String.valueOf(pageNum));
        params.put("pageSize",String.valueOf(pageSize));
        String serialNo = this.equipment_serial_no_editview.getText().toString();
        if(serialNo == null || serialNo.trim().equals(""))
            serialNo = null;
        String equipName = this.equipment_equip_name_editview.getText().toString();
        if(equipName == null || equipName.trim().equals(""))
            equipName = null;
        String sopTime = this.equipment_sop_time.getText().toString();
        if(sopTime == null || sopTime.trim().equals(""))
            sopTime = null;

        String line = this.equipment_line_spinner.getSelectedItem() == null ?
                null : this.equipment_line_spinner.getSelectedItem().toString();
        if(line !=null && line.equals("【请选择】"))
            line = null;
        String station = this.equipment_station_spinner.getSelectedItem() == null ?
                null : this.equipment_station_spinner.getSelectedItem().toString();
        if(station!=null && station.equals("【请选择】"))
            station = null;
        String status = this.equipment_status_spinner.getSelectedItem() == null ?
                null : this.equipment_status_spinner.getSelectedItem().toString();
        if(status!=null && status.equals("【请选择】"))
            status = null;


        if(serialNo!=null)
            params.put("serialNo",serialNo);
        if(equipName!=null)
            params.put("equipName",equipName);
        if(line!=null)
            params.put("line",line);
        if(station!=null)
            params.put("station",station.split("\n")[0]);
        if(status!=null){
            if(status.equals("使用"))
                status = "1";
            else
                status = "0";
            params.put("status",status);
        }

        if(sopTime!=null)
            params.put("sopTime",sopTime);

        equipmentApi.list(OnlineUser.getToken(EquipmentActivity.this),params).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String resultJson = response.body().string();
                    JSONObject result = new JSONObject(resultJson);
                    int code = result.getInt("code");
                    String msg = result.getString("msg");
                    total = result.getLong("total");
                    if (code == 200) {
                        if(initMark)
                            tEquipments.clear();
                        JSONArray jsonArrays = result.getJSONArray("rows");
                        for (int i = 0; i < jsonArrays.length(); i++) {
                            JSONObject jsonObject = jsonArrays.getJSONObject(i);
                            TEquipment tEquipment = new TEquipment();
                            tEquipment.setId(jsonObject.getLong("id"));
                            tEquipment.setSerialNo(jsonObject.getString("serialNo"));
                            tEquipment.setEquipName(jsonObject.getString("equipName"));
                            tEquipment.setQuantity(jsonObject.getLong("quantity"));
                            tEquipment.setUnit(jsonObject.getString("unit"));
                            tEquipment.setLine(jsonObject.getString("line"));
                            tEquipment.setStation(jsonObject.getString("station"));
                            tEquipment.setRemark(jsonObject.getString("remark"));
                            tEquipment.setStatus(jsonObject.getLong("status"));
                            int tIndex = jsonObject.getString("sopTime").indexOf("T");
                            tEquipment.setSopTimeStr(jsonObject.getString("sopTime").substring(0, tIndex));
                            tEquipments.add(tEquipment);
                        }
                        if(initMark){
                            // 创建并设置布局管理器
                            EquipmenteRecycleView.RecycleViewAdapter  recycleViewAdapter = new EquipmenteRecycleView.RecycleViewAdapter(tEquipments);
                            recyclerView.setAdapter(recycleViewAdapter);
                        }else {
                            //通知插入参数是插入位置
                            recyclerView.getAdapter().notifyItemInserted(recyclerView.getAdapter().getItemCount()-1);
                        }

                    } else {
                        throw new RuntimeException(code + ":" + msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                            "系统错误", e.toString(), "确认", null).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                AlertDialogCreator.getConfirmDialog(EquipmentActivity.this,
                        "系统错误", t.toString(), "确认", null).show();
            }
        });
    }


}
